from rest_framework import viewsets, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from common.pagination import CustomerPagination
from system.models import User, UserRole, Role
from system.serializer import UserSerializer, RoleSerializer


# 用户视图集
class UserViewSet(viewsets.ModelViewSet):
    # 指定序列化器类
    serializer_class = UserSerializer
    # 指定权限类， 要求用户认证
    permission_classes = [IsAuthenticated]
    # 使用自定义分页
    pagination_class = CustomerPagination

    # 定义获取查询集的方法
    def get_queryset(self):
        return User.objects.all()

    # 查询用户列表
    def user_list(self, request):
        users = self.get_queryset()  # 获取查询集
        # 将结果分页
        page_queryset = self.paginate_queryset(users)
        serializer = self.get_serializer(page_queryset, many=True)
        return self.get_paginated_response(serializer.data)

    # 获取当前登录用户的信息
    def user_info(self, request):
        user_id = request.auth.payload['id']
        user = User.objects.get(pk=user_id)
        user_role = UserRole.objects.filter(user_id=user_id).first()
        role = Role.objects.filter(id=user_role.role_id).first()
        user_data = {
            **self.get_serializer(user).data,
            'role': RoleSerializer(role).data
        }
        return Response(user_data)

    # 查询用户详情
    def user_detail(self, request):
        user_id = request.GET.get('id', '')
        user = User.objects.filter(pk=user_id).first()  # 获取指定用户对象
        if user:
            user_role = UserRole.objects.filter(user_id=user_id).first()
            role = Role.objects.filter(id=user_role.role_id).first()
            user_data = {
                **self.get_serializer(user).data,
                'role': RoleSerializer(role).data
            }
            return Response(user_data)  # 返回序列化数据
        else:
            return Response({'msg': '用户不存在', 'code': status.HTTP_500_INTERNAL_SERVER_ERROR})

    # 创建用户
    @classmethod
    def user_add(cls, request):
        # 如果请求用户不是管理员，拒绝请求
        if not request.auth.payload['role'] == 'admin':
            return Response({'msg': '只有管理员才可以操作创建用户', 'code': status.HTTP_401_UNAUTHORIZED})

        data = request.data.copy()  # 复制请求数据

        have_user = User.objects.filter(username=data.get('username')).first()
        if have_user:
            return Response({'msg': '当前用户已存在', 'code': status.HTTP_500_INTERNAL_SERVER_ERROR})

        role_id = data.pop('role_id')
        user = User.objects.create_user(**data)
        UserRole.objects.create(**{
            'user_id': user.id,
            'role_id': role_id
        })
        return Response({'msg': '新增用户成功'})  # 返回序列化数据

    # 删除用户
    @classmethod
    def user_del(cls, request):
        # 如果请求用户不是管理员，拒绝请求
        if not request.auth.payload['role'] == 'admin':
            return Response({'msg': '只有管理员才可以操作删除用户', 'code': status.HTTP_401_UNAUTHORIZED})
        user_id = request.GET.get('id')

        have_user = User.objects.filter(pk=user_id).first()  # 获取指定用户对象
        if have_user:
            have_user.delete()
            UserRole.objects.filter(user_id=user_id).delete()
            return Response({'msg': '删除成功'})  # 返回204状态码表示删除成功
        else:
            return Response({'msg': '该用户不存在', 'code': status.HTTP_500_INTERNAL_SERVER_ERROR})

    # 更新用户
    @classmethod
    def user_update(cls, request):
        # 如果请求用户不是管理员且请求的用户ID与当前用户ID不匹配，则拒绝请求
        if not request.auth.payload['role'] == 'admin':
            return Response({'msg': '只有管理员才可以操作用户更新', 'code': status.HTTP_401_UNAUTHORIZED})
        user_id = request.data.get('user_id')

        have_user = User.objects.filter(pk=user_id).first()  # 获取指定用户对象

        if have_user:
            data = request.data.copy()  # 复制请求数据
            user_role_data = {
                'role_id': data.get('role_id'),
                'user_id': data.get('user_id')
            }
            UserRole.objects.filter(user_id=user_id).update(**user_role_data)
            User.objects.filter(pk=user_id).update(**{
                'is_active': data.get('is_active'),
                'username': data.get('username')
            })
            return Response({})
        else:
            return Response({'msg': '该用户不存在', 'code': status.HTTP_500_INTERNAL_SERVER_ERROR})
